package com.idol.logger.core.printer.window.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.idol.logger.core.printer.data.LoggerMo
import com.idol.logger.core.printer.window.panel.IdolLoggerPanel
import com.idol.logger.core.printer.window.panel.IdolTogglePanel

internal class IdolWindowService : Service() {
    companion object {
        const val KEY = "intent_logger_key"
        const val DISPLAY = "intent_logger_display"
    }

    private val togglePanel by lazy {
        IdolTogglePanel(application, ::openClick)
    }

    private val loggerPanel by lazy {
        IdolLoggerPanel(application, ::closeClick)
    }

    private fun openClick() {
        loggerPanel.onAttachedToWindow()
    }

    private fun closeClick() {
        togglePanel.onAttachedToWindow()
    }

    override fun onCreate() {
        super.onCreate()
        togglePanel.onAttachedToWindow()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        intent?.apply {
            getParcelableExtra<LoggerMo>(KEY)?.also {
                loggerPanel.add(it).smoothScrollToPosition(loggerPanel.size() - 1)
            }
            getBooleanExtra(DISPLAY, true).also {
                togglePanel.setVisibility(it)
                loggerPanel.setVisibility(it)
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onBind(intent: Intent): IBinder? = null

    override fun onDestroy() {
        super.onDestroy()
        togglePanel.onDetachedFromWindow()
        loggerPanel.onDetachedFromWindow()
    }

}
